package pl.edu.agh.uddiProxy.types;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import javax.persistence.Column;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

import org.hibernate.annotations.AccessType;
import org.springframework.security.GrantedAuthority;

import pl.edu.agh.uddiProxy.dao.DAOHelper;

@Table(name = "authorities",
	    uniqueConstraints = {@UniqueConstraint(columnNames={"authority"})}
)

@AccessType("field")
@javax.persistence.Entity
public class Authority extends Entity implements GrantedAuthority, Serializable {
	private static final long serialVersionUID = 5708069610438959181L;

	@Column(name = "authority", nullable = false)
	private String authority;

	public static final String ADMIN = "ROLE_ADMIN";
	public static final String USER = "ROLE_USER";
	public static final String COMMON = "ROLE_COMMON";
	public static final String ANONYMOUS = "ROLE_ANONYMOUS";
	
	private static Map<String, Authority> map = new HashMap<String, Authority>();
	
	public Authority() {
	}
	
	public Authority(String authority) {
		this.authority = authority;
	}
	
	public static Authority getAuthority(String authority) {
		if (map.containsKey(authority)) {
			return map.get(authority);
		}
		
		Authority auth = DAOHelper.getUserDAO().getAuthority(authority);
		if (auth == null) {
			auth = new Authority(authority);
		}
		map.put(authority, auth);
		return auth;
	}
	
	public String getAuthority() {
		return authority;
	}

	public void setAuthority(String authority) {
		this.authority = authority;
	}

	public int compareTo(Object a) {
		if (authority == null) {
			return -1;
		}
		if (a instanceof Authority) {
			Authority auth = (Authority) a;
			if (auth.getAuthority() != null) {
				return authority.compareTo(auth.getAuthority());
			}
		}
		return -1;
	}

	@Override
	public String toString() {
		return authority;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result
				+ ((authority == null) ? 0 : authority.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Authority other = (Authority) obj;
		if (authority == null) {
			if (other.authority != null)
				return false;
		} else if (!authority.equals(other.authority))
			return false;
		return true;
	}
	
	
}
